import easyocr
import os
import sys
import json
import io

# 初始化 easyocr 识别器，支持英文
reader = easyocr.Reader(['en'])

# 强制 Python 输出 UTF-8 编码
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')

# 返回结果字典
result_dict = {}

# 参数判断
if len(sys.argv) < 2:
    result_dict['log'] = '请输入图片路径'
    result_dict['code'] = None
    print(json.dumps(result_dict, ensure_ascii=False))
    exit()

imgPath = sys.argv[1]

# 图片路径判断
if not os.path.exists(imgPath):
    result_dict['log'] = '图片不存在'
    result_dict['code'] = None
    print(json.dumps(result_dict, ensure_ascii=False))
    exit()

# 开始识别
ocr_result = reader.readtext(imgPath)

if ocr_result:
    result_dict['log'] = '识别成功'
    result_dict['code'] = ocr_result[0][1]  # 只取第一个识别结果
else:
    result_dict['log'] = '未识别到结果'
    result_dict['code'] = None

# 最后返回 JSON 格式
print(json.dumps(result_dict, ensure_ascii=False))
